package org.onion.pattern.event.springboot.rocketmq.topic;


import org.apache.commons.lang3.StringUtils;
import org.onion.pattern.event.springboot.rocketmq.annotation.RocketMQEvent;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.util.Objects;


@Component
public class DefaultTopicGenerator implements ITopicGenerator {

//    @Override
//    public TopicModel generate(Class<?> aClass) {
//        final String topic = getTopicName(aClass);
//        final String subTopic = getSubTopicName(aClass);
//        final TopicModel topicModel = new TopicModel();
//        topicModel.setTopic(topic);
//        topicModel.setSubTopic(subTopic);
//        Objects.requireNonNull(topicModel.getTopic(), "【领域事件】事件未发现@Topic注解");
//
//        if (StringUtils.isEmpty(subTopic)) {
//            topicModel.setSubTopic("*");
//        }
//        return topicModel;
//    }

    @Override
    public RocketMQTopic generate(Class<?> consumerGroupClass,Class<?> msgClazz) {
        RocketMQEvent rocketMQEvent = AnnotationUtils.findAnnotation(msgClazz, RocketMQEvent.class);

        final String topic = Objects.requireNonNull(rocketMQEvent,"topic 为空").value();
        String subTopic = RocketMQTagUtils.getTag(msgClazz);
        final RocketMQTopic topicModel = new RocketMQTopic();
        topicModel.setTopic(topic);
        topicModel.setTag(StringUtils.defaultIfBlank(subTopic,"*"));
        Objects.requireNonNull(topicModel.getTopic(), "【事件】事件未发现@Topic注解");
        return topicModel;
    }

    //  @Override
//  public TopicModel generateTopic(IEvent event) {
//    return generateTopic(IEvent.class);
//  }

//    private String getTopicName(Class<?> aClass) {
////        if (aClass == null) {
////            return null;
////        }
////        final Optional<Annotation> anno =
////                Arrays.stream(aClass.getAnnotations()).filter(x -> x instanceof Topic).findFirst();
////
////        if (anno.isPresent()) {
////            Topic topic = (Topic) anno.get();
////            if (StringUtils.isEmpty(topic.value())) {
////                return aClass.getName().replace(".", "-");
////            }
////            return topic.value();
////        }
//
//        return getTopicName(aClass.getSuperclass());
//    }

//    private String getSubTopicName(Class<?> aClass) {
////        if (aClass == null) {
////            return null;
////        }
////        final Optional<Annotation> anno =
////                Arrays.stream(aClass.getAnnotations()).filter(x -> x instanceof SubTopic).findFirst();
////
////        if (anno.isPresent()) {
////            SubTopic topic = (SubTopic) anno.get();
////            if (StringUtils.isEmpty(topic.value())) {
////                return aClass.getName().replace(".", "-");
////            }
////            return topic.value();
////        }
//
//        return getSubTopicName(aClass.getSuperclass());
//    }
}
